import util from 'util.js';
/**
 * get方式请求
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
const app = getApp();
function _get(url, data, success, fail) {
  //TODO 添加等待动画
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    url: app.globalData.url + url,
    header: {
      'token': wx.getStorageSync('token'),
      // 'Content-Type': 'application/json'
    },
    data: data,
    success: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      //半段是否为false
      isFalse(res);

      if (res.data.code && res.data.code == '401') {
        timeOutLogin(res)
      }
      success(res);
    },
    fail: function (res) {
      console("失败");
      //TODO 隐藏等待动画
      wx.showToast({
        title: '请求失败',
        image: '../../image/shibai.png',
      })
      fail(res);
    },
    complete: function () {
      // complete
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }
  });
}

function _get_no(url, data, success, fail) {
  //TODO 添加等待动画
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    url: app.globalData.urlc + url,
    header: {
      'token': wx.getStorageSync('token'),
    },
    data: data,
    success: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      //半段是否为false
      isFalse(res);

      if (res.data.code && res.data.code == '401') {
        timeOutLogin(res)
      }
      success(res);
    },
    fail: function (res) {
      console("失败");
      //TODO 隐藏等待动画
      wx.showToast({
        title: '请求失败',
        image: '../../image/shibai.png',
      })
      fail(res);
    },
    complete: function () {
      wx.hideNavigationBarLoading() //完成停止加载
      wx.stopPullDownRefresh() //停止下拉刷新
    }
  });
}
/**
 * post表单方式提交 
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _post_form(url, data, success, fail) {
  //TODO 添加等待动画
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    url: app.globalData.url + url,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'token': wx.getStorageSync('token'),
    },
    method: 'POST',
    data: data ,
    success: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      //半段是否为false
      isFalse(res);
      if (res.data.code && res.data.code == '401') {
        timeOutLogin(res)
      }
      success(res);
    },
    fail: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      wx.showToast({
        title: '请求失败',
        image: '../../image/shibai.png',
      })
      fail(res);
    }
  });
}

/**
 * post表单方式提交 
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _post_form_no(url, data, success, fail) {
  //TODO 添加等待动画
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    url: app.globalData.urlc + url,
    data: data,
    header: {
      'content-type': 'application/x-www-form-urlencoded',
      'token': wx.getStorageSync('token'),
    },
    method: 'POST',
    success: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      //半段是否为false
      isFalse(res);
      if (res.data.code && res.data.code == '401') {
        timeOutLogin(res)
      }
      success(res);
    },
    fail: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      wx.showToast({
        title: '请求失败',
        image: '../../image/shibai.png',
      })
      fail(res);
    }
  });
}

/**
* post json方式提交 
* url 请求地址
* success 成功的回调
* fail 失败的回调
*/
function _post_json(url, data, success, fail) {
  //TODO 添加等待动画
  wx.showLoading({
    title: '加载中...',
  })
  wx.request({
    url: app.globalData.url + url,
    header: {
      'content-type': 'application/json',
      'token': wx.getStorageSync('token'),
    },
    method: 'POST',
    data: data,
    success: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      //半段是否为false
      isFalse(res);
      if (res.data.code && res.data.code == '401') {
        timeOutLogin(res)
      }
      success(res);
    },
    fail: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      wx.showToast({
        title: '网络异常',
        image: '../../image/shibai.png',
      })
      fail(res);
    }
  });
}
/**
* 上传文件
* url 请求地址
* success 成功的回调
*/
function _upload_file(url, file, filename, data, success) {
  wx.showLoading({
    title: '提交中...',
  })
  wx.uploadFile({
    url: app.globalData.url + url,
    filePath: file,
    name: filename,
    formData: data,
    header: {
      'token': wx.getStorageSync('token'),
    },
    success: function (res) {
      wx.hideLoading();
      var result = JSON.parse(res.data);
      //半段是否为false
      isFalse(res);
      //登录超时
      if (res.data.code && res.data.code == '401') {
        timeOutLogin(res)
      }
      if (result.success) {
        wx.hideLoading();
      } else {
        wx.showToast({
          title: res.msg ? res.msg : '上传失败',
          image: '../../image/shibai.png',
        })
      }
      success(result);
    },
    fail: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      wx.showToast({
        title: '提交失败' + res.data,
        image: '../../image/shibai.png',
      })
    }

  })
}

/**
* post post表单方式提交
* url 请求地址
* success 成功的回调
*/
function _post_data(url, data, success) {
  _post_form(url, data, success, function (res) { })
}

/**
 * get方式请求
 * url 请求地址
 * success 成功的回调
 * fail 失败的回调
 */
function _get_data(url, data, success) {
  _get(url, data, success, function (res) { })
}
//判断是否为false
function isFalse(res) {
  if (res.data.success == false) {
      //判断是否未审核
      if (res.data.code && res.data.code == '503') {
        app.globalData.isAudit = true;
        wx.showModal({
          title: '提示',
          content: res.data.msg,
        })
      }
    if (res.data.msg) {
      wx.showToast({
        title: res.data.msg ? res.data.msg : '未知异常',
        image: '../../image/shibai.png',
      })
    } else {
      wx.showToast({
        title: res.data.code ? res.data.code + '' : res.statusCode + '',
        image: '../../image/shibai.png',
        duration: 3000
      })
    }
  } 


}
//计算两个时间的月数差
function getMonths(date1, date2) {
  //用-分成数组
  date1 = date1.split("-");
  date2 = date2.split("-");
  //获取年,月数,
  var year1 = parseInt(date1[0]),
    month1 = parseInt(date1[1]),
    year2 = parseInt(date2[0]),
    month2 = parseInt(date2[1]),
    //通过年,月差计算月份差
    months = (year2 - year1) * 12 + (month2 - month1);
  return months;
}
//验证手机号码
function checkMobile(str) {
  var
    re = /^1\d{10}$/
  if (re.test(str)) {
    return true;
  } else {
    return false;
  }
}
//验证手机
function isPoneAvailable(str) {
  var myreg = /^[1][3,4,5,7,8][0-9]{9}$/;
  if (!myreg.test(str)) {
    return false;
  } else {
    return true;
  }
}

//验证身份证
function IdentityCodeValid(code) {
  var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
  var tip = "";
  var pass = true;

  if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
    tip = "身份证号格式错误";
    pass = false;
  }

  else if (!city[code.substr(0, 2)]) {
    tip = "地址编码错误";
    pass = false;
  }
  else {
    //18位身份证需要验证最后一位校验位
    if (code.length == 18) {
      code = code.split('');
      //∑(ai×Wi)(mod 11)
      //加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
      var sum = 0;
      var ai = 0;
      var wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = code[i];
        wi = factor[i];
        sum += ai * wi;
      }
      var last = parity[sum % 11];
      if (parity[sum % 11] != code[17]) {
        tip = "校验位错误";
        pass = false;
      }
    }
  }
  if (!pass) alert(tip);
  return pass;
}

//超时
function timeOutLogin(res) {
  if (res.data.code = "401") {
    app.globalData.isLogin = false;
    autoLogin(getLogin);
  }
}

//自动登陆 
function autoLogin(toLogin) {
  wx.showLoading({
    title: '登录...',
  })
  // var userwx = wx.getStorageSync('user')
  // if (userwx){
  //   toLogin(userwx);
  //   return;
  // }
  var that = this;
  wx.login({
    success: function (res) {
      wx.getSetting({
        success(setRes) {
          // 判断是否已授权  
          if (!setRes.authSetting['scope.userInfo']) {
            // 授权访问  
            wx.authorize({
              scope: 'scope.userInfo',
              success() {
                //获取用户信息  
                wx.getUserInfo({
                  lang: "zh_CN",
                  success: function (userRes) {
                    //发起登录请求  
                    var params = {
                      code: res.code,
                      encryptedData: userRes.encryptedData,
                      iv: userRes.iv
                    }
                    // wx.setStorageSync('user', params)
                    toLogin(params);
                  }
                })
              },
              fail:function(res){
                //获取用户信息  
                //TODO 隐藏等待动画
                wx.hideLoading();
                wx.showToast({
                  title: res.errMsg,
                  image: '../../image/shibai.png',
                })
              }
            })

          } else {
            //获取用户信息  
            wx.getUserInfo({
              lang: "zh_CN",
              success: function (userRes) {
                //发起登录请求  
                var params = {
                  code: res.code,
                  encryptedData: userRes.encryptedData,
                  iv: userRes.iv
                }
                //缓存到本地
                // wx.setStorageSync('user', params)
                toLogin(params);
              }
            })
          }
        }
      })
    },
    fail: function (res) {
      //TODO 隐藏等待动画
      wx.hideLoading();
      wx.showToast({
        title: '请求失败',
        image: '../../image/shibai.png',
      })
    }
  })
}

//登录
var getLogin = function(params) {
  var that = this;
  var that = this;
  _post_form_no('/wx/landlord/login', params,
    //成功
    function (res) {
      if (res.data.success) {
        wx.setStorageSync('refresh', 'refresh');
        wx.setStorageSync('result', 'result');
        wx.setStorageSync('token', res.data.token);
        app.globalData.isLogin = true;
      } else {
        if (res.data.token && res.data.token != '') {
          wx.showToast({
            title: res.data.msg,
            image: '../../image/shibai.png'
          })
          wx.setStorageSync('utoken', res.data.token);
        }
      }
    });
}




module.exports = {
  // _get_data: _get,
  // _post: _post_form,
  _get: _get_data,
  _get_no: _get_no,
  _post: _post_data,
  _post_no:_post_form_no,
  _post_json: _post_json,
  _upload_file: _upload_file,
  getMonths: getMonths,
  checkMobile: checkMobile,
  autoLogin:autoLogin,
  IdentityCodeValid: IdentityCodeValid
}